//
//  EventListViewController.swift
//  GiteeClient
//
//  Created by 王志标 on 2020/11/2.
//

import UIKit
import MJRefresh
import AwaitKit
import PKHUD
import UITableView_FDTemplateLayoutCell
import SnapKit


enum EventType {
    case OTHER
    case OWNER
}

/// event 列表控制器
class EventListViewController: BaseViewController {

    var eventTableView:UITableView!
    var cellID = "eventtablecellid"
    var eventArray:[EventMdoel]?
    var currentPage = 1
    
    var userModel:UserModel?
    var eventType:EventType = .OWNER
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    init(user:UserModel? = nil,type: EventType = .OWNER) {
        super.init(nibName: nil, bundle: nil)
        self.userModel = user
        self.eventType = type
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        eventTableView.frame = view.bounds
    }
    
}

// MARK: - 设置界面
extension EventListViewController {
    
    func setupUI() {
        
        eventTableView = UITableView()
        eventTableView.register(UINib.init(nibName: "EventTableViewCell", bundle: nil), forCellReuseIdentifier: cellID)
        let value = UIView.AutoresizingMask.flexibleHeight.rawValue | UIView.AutoresizingMask.flexibleWidth.rawValue
        eventTableView.autoresizingMask = UIView.AutoresizingMask.init(rawValue: value)
        eventTableView.delegate = self
        eventTableView.dataSource = self
        eventTableView.separatorStyle = .none
        view.addSubview(eventTableView)
        
        eventTableView.snp.makeConstraints { (make) in
            make.top.left.right.bottom.equalToSuperview()
        }
        
        let mjH = MJRefreshNormalHeader {
            self.currentPage = 1
            self.loadData(page: self.currentPage)
        }
        mjH?.lastUpdatedTimeLabel.isHidden = true
        eventTableView.mj_header = mjH
        mjH?.beginRefreshing()
        
        let mjF = MJRefreshBackNormalFooter {
            self.currentPage += 1
            self.loadData(page: self.currentPage)
        }
        eventTableView.mj_footer = mjF
        
        
        eventTableView.emptyDataSetDelegate = self
        eventTableView.emptyDataSetSource = self
        
        if #available(iOS 13.0, *) {
            eventTableView.backgroundColor = Colors.backgroundColor
        }
    }
}

// MARK: - 加载数据
extension EventListViewController {
    
    // 下拉刷新加载数据
    func loadData(page: Int){
        
        var url = URLs.V3URL + URLs.EVENTS
        if self.eventType == .OTHER {
            url += "user/" + self.userModel!.id.description
        }
        url += "?page=\(page)"
        
        // 异步加载
        DispatchQueue.global().async {
        
            let result:Result<[EventMdoel?]> = NetWorkTool.shared.getArrayRequest(url: url, parameters: nil)
            
            DispatchQueue.main.async {
                if result.code == 0 {
                    if page == 1 {
                        self.eventArray = result.data as? [EventMdoel]
                    }else {
                        self.eventArray?.append(contentsOf: (result.data as? [EventMdoel])!)
                        if result.data?.count == 0 {
                            self.eventTableView.mj_footer.endRefreshingWithNoMoreData()
                            return
                        }
                    }
                    self.eventTableView.reloadData()
                }else {
                    HUD.flash(.label(result.message), delay: 2.0)
                }
                self.eventTableView.mj_header.endRefreshing()
                self.eventTableView.mj_footer.endRefreshing()
            }
        }
    }
    
    func resetData(){
        self.eventArray = [EventMdoel]()
        self.eventTableView.reloadData()
        self.eventTableView.mj_header.endRefreshing()
        self.eventTableView.mj_footer.endRefreshing()
        
    }
    
}

// MARK: - tableview的代理和数据源方法
extension EventListViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return eventArray?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! EventTableViewCell
      
        cell.selectionStyle = .none
        cell.model = eventArray![indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        
        
        return tableView.fd_heightForCell(withIdentifier: cellID) { (cell) in
            
            (cell as! EventTableViewCell).selectionStyle = .none
            (cell as! EventTableViewCell).model = self.eventArray![indexPath.row]
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let event = self.eventArray![indexPath.row]
        
        if event.target_type != nil && (event.target_type == "Issue" || event.target_type == "Note") {
            
            if event.events.issue == nil {
                let detialVC = ProjectDetialViewController(project: event.project)
                detialVC.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(detialVC, animated: true)
            }else {
                let detialVC = IssueDetialViewController(model: event.events.issue!, titles: ["详情","评论"])
                detialVC.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(detialVC, animated: true)
            }
        }else {
            let detialVC = ProjectDetialViewController(project: event.project)
            detialVC.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(detialVC, animated: true)
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.listViewDidScrollCallback?(scrollView)
    }
}

extension EventListViewController: JXPagingViewListViewDelegate {
    public func listView() -> UIView {
        return self.view
    }
    
    public func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        self.listViewDidScrollCallback = callback
    }

    public func listScrollView() -> UIScrollView {
        return self.eventTableView
    }
}

